package com.twu.biblioteca.presenter;

import com.twu.biblioteca.events.HasEventListener;
import com.twu.biblioteca.events.Listener;
import com.twu.biblioteca.model.item.exceptions.InexistantItemException;
import com.twu.biblioteca.model.exceptions.ItemAlreadyReservedException;
import com.twu.biblioteca.model.item.ItemID;
import com.twu.biblioteca.model.LibraryCatalogue;
import com.twu.biblioteca.model.session.Session;

/**
 * Created with IntelliJ IDEA.
 * User: cschlumb
 * Date: 08/08/2013
 * Time: 13:31
 * To change this template use File | Settings | File Templates.
 */
public class ReservationPresenter implements Presenter {

    public interface Display extends HasEventListener{
        public void prompt();
        public void successMessage();
        public void failMessage();
        public ItemID getItemSelection();
    }

    private final LibraryCatalogue libraryCatalogue;
    private final Display view;

    public ReservationPresenter(LibraryCatalogue libraryCatalogue, Display view) {
        this.libraryCatalogue = libraryCatalogue;
        this.view = view;
    }

    @Override
    public void go(Session session) {
        bind();
        view.prompt();
    }

    void processInput(ItemID itemID){
        try {
            libraryCatalogue.reserve(itemID);
            view.successMessage();
        } catch (InexistantItemException e) {
            view.failMessage();
        } catch (ItemAlreadyReservedException e) {
            view.failMessage();
        }
    }

    private void bind(){
        view.addEventListener(new Listener() {
            @Override
            public void onEvent() {
                processInput(view.getItemSelection());
            }
        });
    }
}
